package dai.samples.mybatis.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

/**
 *
 * @author daify
 * @date 2019-08-01
 **/
@Component
@Intercepts({
        // 拦截Executor的query的操作
        @Signature(
                type = ParameterHandler.class,
                method = "setParameters",
                args = { PreparedStatement.class}
        )
})
@Slf4j
public class ExecutorParameterPlugin implements Interceptor {
    
    @Override 
    public Object intercept(Invocation invocation) throws Throwable {
        Method method = invocation.getMethod();
        log.info("ExecutorParameterPlugin拦截内容，拦截类:{},拦截方法:{}",
                method.getDeclaringClass().getName(),method.getName());

        Object[] args = invocation.getArgs();
        PreparedStatement statements = (PreparedStatement) args[0];
        ParameterMetaData parameterMetaData = statements.getParameterMetaData();
        ResultSet generatedKeys = statements.getGeneratedKeys();

        // 主要的业务
        return invocation.proceed();
    }

    /**
     * 将这个类作为包装类假如拦截链
     * @param o
     * @return
     */
    @Override 
    public Object plugin(Object o) {
        return Plugin.wrap(o, this);
    }

    /**
     * 设置参数
     * @param properties
     * @return
     */
    @Override 
    public void setProperties(Properties properties) {

    }
}
